﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project.Data;
using Project.Data.Repository;
using Project.Model.EF6.Entity;
using Project.Model.EF6.ViewModel;
using Project.Services.Tools;
using System.IO;

namespace Project.Services
{
    public static class PeopleService2
    {
        public static string GetData(DateTime date)
        {
            int count = 0;
            var end = date.AddDays(1);
            //获取今天是今年第几周
            GregorianCalendar gc = new GregorianCalendar();
            int weekOfYear = gc.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            var dayOfWeek = (int)date.DayOfWeek;
            dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
            var weekBegin = date.AddDays(1 - dayOfWeek);
            var weekEnd = weekBegin.AddDays(6);
            var monthBegin = date.AddDays(1 - date.Day);
            var monthEnd = monthBegin.AddMonths(1).AddDays(-1);
            try
            {
                var day = Config.DayPlan;
                var week = Config.WeekPlan;
                var month = Config.MonthPlan;
                var rep = new DbContextRepository<EfContext>();
                var list = rep.QueryList<ViscosityViewModel>(
                                "Select OPENID,count(QR_CODE) AS COUNT From T_SGM_XLW_SALES_RECORD Where SCAN_TIME > TO_DATE('" +
                                date + "','yyyy-mm-dd hh24:mi:ss') And SCAN_TIME <=TO_DATE('" + end +
                                "','yyyy-mm-dd hh24:mi:ss') group by OPENID");
                //UserOverView  临时统计表数据
                foreach (var n in list)
                {
                    var user = rep.Find<UserOverview>(m => m.OPENID == n.OPENID);
                    if (user != null)
                    {
                        if (date >= user.BEGINDATE && date <= user.ENDDATE)
                        {
                            user.WEEKCOUNT += n.COUNT;
                            user.MONTHCOUNT += n.COUNT;
                        }
                        else
                        {
                            user.WEEKCOUNT = n.COUNT;
                            user.MONTHCOUNT = n.COUNT;
                            user.BEGINDATE = weekBegin;
                            user.ENDDATE = weekBegin.AddDays(6);
                        }
                        user.ROW_UPDATE_DATE = date;
                        var dateArry = user.SCAN_DATE.Split(',').ToList();
                        var scanArry = user.SCAN_ARRY.Split(',').ToList();
                        foreach (var m in dateArry)
                        {
                            var index = dateArry.IndexOf(m);
                            var temp = DateTime.Parse(m);
                            if ((date - temp).Days > 30)
                            {
                                dateArry.Remove(m);
                                scanArry.Remove(scanArry[index]);
                            }
                        }
                        user.SCAN_ARRY = string.Join(",", scanArry) + "," + n.COUNT;
                        user.SCAN_DATE = string.Join(",", dateArry) + "," + date.ToString("yyyy-MM-dd");
                        rep.Update<UserOverview>(user, false);
                    }
                    else
                    {
                        var model = new UserOverview
                        {
                            OPENID = n.OPENID,
                            WEEKCOUNT = n.COUNT,
                            MONTHCOUNT = n.COUNT,
                            BEGINDATE = weekBegin,
                            ENDDATE = weekBegin.AddDays(6),
                            SCAN_ARRY = n.COUNT.ToString(),
                            SCAN_DATE = date.ToString("yyyy-MM-dd")
                        };
                        rep.Add<UserOverview>(model, false);
                    }
                }
                //用户粘性天数统计
                var dayViscosity = new List<ViscosityDay>();
                for (int i = 0; i < day.Length; i++)
                {
                    if (day[i].Contains("-"))
                    {
                        var arry = day[i].Split('-');
                        int min = int.Parse(arry[0]);
                        int max = int.Parse(arry[1]);
                        var viscosityDay = new ViscosityDay
                        {
                            NAME = day[i] + "次",
                            COUNT = list.Where(m => m.COUNT >= min && m.COUNT <= max).ToList().Count,
                            SORT = min,
                            ROW_UPDATE_DATE = date
                        };
                        dayViscosity.Add(viscosityDay);
                        if (i == day.Length - 1)
                        {
                            var viscosityDay2 = new ViscosityDay
                            {
                                NAME = max + "次以上",
                                COUNT = list.Where(m => m.COUNT > max).ToList().Count,
                                SORT = max,
                                ROW_UPDATE_DATE = date
                            };
                            dayViscosity.Add(viscosityDay2);
                        }
                    }
                    else
                    {
                        var salesCount = int.Parse(day[i]);
                        var viscosityDay = new ViscosityDay
                        {
                            NAME = day[i] + "次",
                            COUNT = list.Where(m => m.COUNT == salesCount).ToList().Count,
                            SORT = int.Parse(day[i]),
                            ROW_UPDATE_DATE = date
                        };
                        dayViscosity.Add(viscosityDay);
                    }
                }
                var flag = rep.Add<ViscosityDay>(dayViscosity);
                if (flag)
                {
                    var weekViscosity = new List<ViscosityWeek>();
                    var monthViscosity = new List<ViscosityMonth>();
                    for (int i = 0; i < week.Length; i++)
                    {
                        var arry = week[i].Split('-');
                        int min = int.Parse(arry[0]);
                        int max = int.Parse(arry[1]);
                        var timeName = week[i] + "次";
                        var overView = rep.FindAll<UserOverview>(m => m.BEGINDATE == weekBegin && m.ENDDATE == weekEnd&&m.WEEKCOUNT>=min&&m.WEEKCOUNT<=max);
                        var weekQuery=rep.Find<ViscosityWeek>(m=>m.NAME== timeName && m.WEEK_BEGIN==weekBegin&&m.WEEK_END==weekEnd);
                        if (weekQuery == null)
                        {
                            weekQuery=new ViscosityWeek
                            {
                                NAME=week[i]+"次",
                                WEEK_BEGIN=weekBegin,
                                WEEK_END = weekEnd,
                                CURRENT_WEEK = weekOfYear,
                                SORT=min,
                                COUNT = overView.Count,
                                ROW_UPDATE_DATE = date
                            };
                            weekViscosity.Add(weekQuery);
                        }
                        else
                        {
                            weekQuery.COUNT = overView.Count;
                            rep.Update(weekQuery, false);
                        }
                        if (i == week.Length - 1)
                        {
                            var maxTimeName = max + "次以上";
                            var overViewWeekMax = rep.FindAll<UserOverview>(m => m.BEGINDATE == weekBegin && m.ENDDATE == weekEnd && m.WEEKCOUNT >max);
                            var weekMax = rep.Find<ViscosityWeek>(m => m.NAME == maxTimeName && m.WEEK_BEGIN == weekBegin && m.WEEK_END == weekEnd);
                            if (weekMax == null)
                            {
                                weekMax = new ViscosityWeek
                                {
                                    NAME = max + "次以上",
                                    COUNT = overViewWeekMax.Count,
                                    SORT = max,
                                    ROW_UPDATE_DATE = date,
                                    WEEK_BEGIN = weekBegin,
                                    WEEK_END = weekEnd,
                                    CURRENT_WEEK = weekOfYear,
                                };
                                weekViscosity.Add(weekMax);
                            }
                            else
                            {
                                weekMax.COUNT = overViewWeekMax.Count;
                                rep.Update<ViscosityWeek>(weekMax,false);
                            }
                        }
                    }
                    rep.Add<ViscosityWeek>(weekViscosity);

                    //用户粘性月统计
                    for (int i = 0; i < month.Length; i++)
                    {
                        var timeName = month[i] + "次";
                        var arry = month[i].Split('-');
                        int min = int.Parse(arry[0]);
                        int max = int.Parse(arry[1]);
                        var overView = rep.FindAll<UserOverview>(m => m.ROW_UPDATE_DATE >= monthBegin && m.ROW_UPDATE_DATE <= monthEnd && m.MONTHCOUNT >= min && m.MONTHCOUNT <= max);
                        var monthQuery = rep.Find<ViscosityMonth>(m => m.NAME == timeName && m.MONTH_BEGIN == monthBegin && m.MONTH_END == monthEnd);
                        if (monthQuery == null)
                        {
                            monthQuery = new ViscosityMonth
                            {
                                NAME = month[i] + "次",
                                MONTH_BEGIN = monthBegin,
                                MONTH_END = monthEnd,
                                CURRENT_MONTH = date.Month,
                                SORT = min,
                                COUNT = overView.Count,
                                ROW_UPDATE_DATE = date
                            };
                            monthViscosity.Add(monthQuery);
                        }
                        else
                        {
                            monthQuery.COUNT = overView.Count;
                            rep.Update(monthQuery, false);
                        }
                        if (i == month.Length - 1)
                        {
                            var maxTimeName = max + "次以上";
                            var overViewMonthMax = rep.FindAll<UserOverview>(m => m.ROW_UPDATE_DATE >= monthBegin && m.ROW_UPDATE_DATE <= monthEnd && m.MONTHCOUNT > max);
                            var monthMax = rep.Find<ViscosityMonth>(m => m.NAME == maxTimeName && m.MONTH_BEGIN == monthBegin && m.MONTH_END == monthEnd);
                            if (monthMax == null)
                            {
                                monthMax = new ViscosityMonth
                                {
                                    NAME = max + "次以上",
                                    COUNT = overViewMonthMax.Count,
                                    SORT = max,
                                    ROW_UPDATE_DATE = date,
                                    MONTH_BEGIN = monthBegin,
                                    MONTH_END = monthEnd,
                                    CURRENT_MONTH = date.Month,
                                };
                                monthViscosity.Add(monthMax);
                            }
                            else
                            {
                                monthMax.COUNT = overViewMonthMax.Count;
                                rep.Update<ViscosityMonth>(monthMax, false);
                            }
                        }
                    }
                    if (rep.Add<ViscosityMonth>(monthViscosity))
                    {
                        return "成功！";
                    }
                    return "失败~";

                }
                else
                {
                    "ViscosityDay插入失败".WriteLog();
                    return "ViscosityDay插入失败";
                }
            }
            catch (Exception ex)
            {
                ex.ErrorHandle();
                return "异常";
            }
        }
    }
}
